import os, copy, wx
from decimal import Decimal as Dec
import decimal

from GUIBudgetNotebook import BudgetGridNotebook
from SqliteHandler import SqliteHandler
from Table4rate import Table4rate
from Table2rate import Table2rate
from Table5rate import Table5rate
from Table1rate import Table1rate
from DataTool import DataTool

class FrontDataHandler:
    
    default_style = {
                    'book1':('表一', ('表二', '表二（标）'), '表二', ('表三', '表三甲'), '表三乙', ('表三乙', '表三丙'), ('表四', '表四设备'), ('表四', '表四材料'), '表五', ),
                    'book2':('表一', ('表二', '表二（标）'), '表二', ('表三', '表三甲'), '表三乙', ('表三乙', '表三丙'), ('表四', '表四设备'), ('表四', '表四材料'), '表五', ),
                    'book3':('表一', ('表二', '表二（标）'), '表二', ('表三', '表三甲'), '表三乙', ('表三乙', '表三丙'), ('表四', '表四设备'), ('表四', '表四材料'), '表五', ),
                    'book4':('表一', ('表二', '表二（标）'), '表二', ('表三', '表三甲'), '表三乙', ('表三乙', '表三丙'), ('表四', '表四设备'), ('表四', '表四材料'), '表五', ),
                    'book5':('表一', ('表二', '表二（标）'), '表二', ('表三', '表三甲'), '表三乙', ('表三乙', '表三丙'), ('表四', '表四设备'), ('表四', '表四材料'), '表五', ),
                    }

    material_type = ['光缆', '电缆', '塑料', '木材', '水泥', '其他', '设备', '设备(不安装)']

    default_mat_dis = {'光缆': 0, '电缆': 0, '塑料': 0, '木材': 0, '水泥': 0, '其他': 0, '设备': 0, '设备(不安装)': 0}

    deafult_elevtion_rate = { 2000: (1.13, 1.29), 3000: (1.30, 1.54), 4000: (1.37, 1.84), }

    pip_survey_quota = {'TGD1-001'}
    bury_survey_quota = {'TXL1-001'}
    common_survey_quota = {'TXL1-002', 'TXL1-003'}
    underw_survey_quota = {}
    unders_survey_quota = {'TXL1-004'}
    # InitDatas中value为默认值
    InitDatas = {'sc2en_dis': 0, 'local': '其他', 'elevation': 0, 'specarea': None,
                 'earth': 0, 'earth_dis': 0, 'mach_dis': 0, 'ton': 0,
                 'steam': 0, 'hasout': 0, 'needinstall': 1, 'sewage': 0,
                 'contax': 0.09, 'matetax':0.13, 'servtax': 0.06, 'othertax1': 0.06,
                 'othertax2': 0.06, 'othertax3': 0.06, 'mat_dis': default_mat_dis,
                 'table3_specarea': '无', 'table3_specarea_rate': 0, 'discount': 100,
                 'discountd': '1', 'discounts': '1', 'discountss': '1', 'discounta': '1',
                 'discountsafe': '1', 'stage_rate': '1'}

    def __init__(self, parent, pro, *args, **kwargs):
        # pro 为分册
        # kwargs 中：path为sqlite绝对路径； sc2en_dis为现场到企业距离（km）；
        # local为省份； elevation为海拔高度；specarea:特殊地区（1，2，3）；
        # earth运土费(元/吨*千米)； earth_dis为运土工程量（吨*千米）；
        # mach_dis为大型机械调遣距离（km）； ton为大型机械吨位； steam为水电蒸汽费
        # hasout 为book1与2 是否有室外部分； needinstall 为是否需要安装设备；
        # sewage 为工程排污费； contax 为施工单位增值税； mat_dis 为材料运距 dict()
        # matetax 为材料增值税 servtax 为服务费增值税 
        # discount 为施工折扣 discountd 为设计折扣 discountss 为勘察折扣 discounts 为监理折扣
        # discounta 为审计折扣 discountsafe 为安全生产费折扣
        self.dbdict = {'表三甲':[[]] , '表三乙':[[]] , '表三丙':[[]] , '表四材料':[[]] , '表四设备':[[]] }
        self.fdict = copy.deepcopy(self.dbdict)
        self.pro = pro
        self.path = kwargs.get('path')
        for name in self.InitDatas:
            value = kwargs.get(name, self.InitDatas[name])
            setattr(self, name, value)
        self.windowname = kwargs.get('windowname', '*')
        # 拆除系数字典
        self.teardict = dict()
        # Init之后需要的数据 materABC为甲供乙供利旧主材除税价
        self.mech = 0
        self.work = 0
        self.mach = 0
        self.meter = 0 
        self.materA = copy.deepcopy(self.default_mat_dis)
        self.materB = copy.deepcopy(self.default_mat_dis)
        self.materC = copy.deepcopy(self.default_mat_dis)
        # 是否第一次执行
        self.initflag = True
        # 是否手动更新表二

        self.sql_quota = SqliteHandler(os.path.join(self.path, 'quota.db'))
        self.InitTableData()
        self.InitGrid(parent)

        self.sql_quota.close()

    def InitTableData(self):
        for i in self.dbdict:
            # name = i
            # data = self.sql_quota.select(name, flag='list')
            data = self.sql_quota.select(i, flag='list')
            self.listdeler(data, 1, self.pro)
            self.dbdict[i] = data
        self.fdict = copy.deepcopy(self.dbdict)
        self.InitTable3()
        self.InitTable4()
        self.InitTable2()
        self.InitTable5()
        self.InitTable1()
    
    def InitTable1(self):
        namelist = [
                    '工程费', '工程建设其他费', '合计',
                    '预备费', '建设利息', '总计', '其中回收费用'
                    ]
        
        A, B, C = copy.deepcopy(self.materA), copy.deepcopy(self.materB), copy.deepcopy(self.materC)
        # 需要安装设备费
        Ae = A.pop('设备')
        Be = B.pop('设备')
        Ce = C.pop('设备')
        equ = Ae + Be + Ce
        equ = Dec(str(round(equ, 2)))
        equtax = Ae * Dec(str(self.matetax)) + Be * Dec(str(self.contax))
        equtax = Dec(str(round(equtax, 2)))
        # 建筑安装工程费
        if self.initflag:
            concost = Dec('0.0')
            concosttax = Dec('0.0')
            path = os.path.join(self.path, 'rate.db')
            ratedata = Table1rate(self.pro, path=path)
            self.table1rate = ratedata.getrate()
            reserve = self.table1rate['预备费'] / 100
            interest = self.table1rate['建设利息'] / 100
        else:
            reserve = self.table1rate['预备费'] / 100
            interest = self.table1rate['建设利息'] / 100
            lenrow = len(self.table2flist)
            lencol = len(self.table2flist[0])
            concost = Dec(str(self.table2flist[0][3]))
            concosttax = Dec(str(self.table2flist[lenrow - 1][lencol - 1]))
        # 其他费用
        othercost = Dec('0')
        othercosttax = Dec('0')
        for i in self.table5flist:
            if i[0] == '总计':
                othercost = Dec(str(i[2]))
                othercosttax = Dec(str(i[3]))
        # 预备费
        reserve = round((equ + concost + othercost) * Dec(str(reserve)), 2)
        # 建设利息
        interest = round((equ + concost + othercost) * Dec(str(interest)) / 2, 2)
        # 其中回收费用
        recycle = round(self.sum_dict(self.materC), 2)

        self.table1flist = []
        equcon = round(equ + concost, 2)
        equcontax = round(equtax + concosttax, 2)
        tequcon = round(equcon + equcontax, 2)
        tothercost = round(othercost + othercosttax, 2)
        subtotal = round(equcon + othercost, 2)
        subtax = round(equcontax + othercosttax, 2)
        subttotal = round(subtotal + subtax, 2)
        total = round(subtotal + reserve + interest- recycle, 2)
        ttotal = round(total + subtax,2)
        temp = [
                ['', equ, '', concost, '', '', equcon, equcontax, tequcon],
                ['', '', '', '', othercost, '', othercost, othercosttax, tothercost],
                ['', '', '', '', '', '', subtotal, subtax, subttotal],
                ['', '', '', '', '', reserve, reserve, '', reserve],
                ['', '', '', '', '', '', interest, '', interest],
                ['', '', '', '', '', '', total, subtax, ttotal],
                ['', '', '', '', '', '', -recycle, '', -recycle],
                ]
        for row, name in enumerate(namelist):
            temp1 = []
            temp1.append('')
            temp1.append(name)
            temp1.extend(temp[row])
            self.table1flist.append(temp1)


    def InitTable2(self):
        
        table2obj = Table2rate(
            self.pro, sc2en_dis=self.sc2en_dis, local=self.local,
            specarea=self.specarea, earth=self.earth, mach_dis=self.mach_dis,
            ton=self.ton, path=os.path.join(self.path, 'rate.db'),
            mech=self.mech, work=self.work)
        
        if self.initflag:
            self.table2rate = table2obj.getrate()
            self.table2disable = copy.deepcopy(self.table2rate)
            self.feefillinall(self.table2disable, 0)
            conn = SqliteHandler(os.path.join(self.path, 'rate.db'))
            self.table2ratedisc = conn.select('description', flag='list')
            
            conn.close()
        
        csfee = self.table2disable['直接费']['措施费']
        for i in csfee:
            if csfee[i] == 1:
                self.table2rate['直接费']['措施费'][i]\
                     = table2obj.getrate()['直接费']['措施费'][i]

        ratedatas = self.table2rate
        ratedata = copy.deepcopy(ratedatas)

        ratedisc = self.table2ratedisc
        
        filldicts = copy.deepcopy(ratedata)
        filldict = copy.deepcopy(ratedata)
        tabledict = {'表二（标）': filldicts, '表二': filldict}
        addtuple = ('建筑安装工程费(除税价)', '建筑安装工程费(含税价)')
        addlist = []
        for row, rowv in enumerate(ratedisc):
            if rowv[1] in addtuple:
                addlist.append(row)
        for table in tabledict:
            tempdict = dict()
            for i in addlist:
                tempdict[ratedisc[i][1]] = Dec('0')
            tempdict['orgin'] = tabledict[table]
            if table != '表二':
                filldicts = tempdict
            else:
                tempdict['orgin'].pop('销项税额')
                tempdict['orgin'].update({'销项税额(折后)': Dec('0')})
                ratedata.pop('销项税额')
                ratedata.update({'销项税额(折后)': Dec('0')})
                filldict = tempdict
                dfilldicts = copy.deepcopy(ratedata)
        dfilldicts = copy.deepcopy(filldicts)
        dfilldict = copy.deepcopy(filldict)
        ratediscs = copy.deepcopy(ratedisc)
        self.table2datadeal(ratedatas, ratediscs, filldicts, dfilldicts, 100)
        self.table2datadeal(ratedata, ratedisc, filldict, dfilldict, self.discount)
        flist = self.dict2list(filldict, dfilldict, l=[])
        flists = self.dict2list(filldicts, dfilldicts, l=[])
        self.table2flist = self.sepratetable2list(flist)
        self.table2flists = self.sepratetable2list(flists)


    def InitTable3(self):
        # 拆除系数字典
        flist = self.fdict['表三甲']
        for i in flist:
            self.teardict[i[5] + '-' + '0'] = [*i[10: 13]]
        
        # self.orginnum = 0
        # 表三甲
        flist = self.fdict['表三甲']
        for index, l in enumerate(flist):
            temprow = [*l[5:8], '0', *l[8:10], '0.0', '0.0', '', l[10], '', '0']
            flist[index] = temprow
        if len(flist) == 0:
            return
        emtyrow = self.genseparaterow(flist)
        flist.append(emtyrow)
        adjustrow = self.gentable3adjustrow(flist)
        flist.append(adjustrow)
        spicrow = self.genspicaerarow(flist)
        flist.append(spicrow)
        sumrow = self.gentable3sumrow(flist)
        flist.append(sumrow)
        self.fdict['表三甲'] = flist
        # 表三乙
        flist = self.fdict['表三乙']
        for index, l in enumerate(flist):
            temprow = [*l[2:5], '0', *l[5:8], '0.0', '0.0', '', l[8], '0', '1']
            flist[index] = temprow
        emtyrow = self.genseparaterow(flist)
        flist.append(emtyrow)
        spicrow = self.genspicaerarow(flist)
        flist.append(spicrow)
        sumrow = self.gentable3sumrow(flist)
        flist.append(sumrow)
        self.fdict['表三乙'] = flist

        # 表三丙
        flist = self.fdict['表三丙']
        for index, l in enumerate(flist):
            temprow = [*l[2:5], '0', *l[5:8], '0.0', '0.0', '', l[8], '0', '1']
            flist[index] = temprow
        emtyrow = self.genseparaterow(flist)
        flist.append(emtyrow)
        sumrow = self.gentable3sumrow(flist)
        flist.append(sumrow)
        self.fdict['表三丙'] = flist

    def InitTable4(self):
        # 设备表
        for tablename in ['表四材料', '表四设备']:
            flist = self.fdict[tablename]
            for index, l in enumerate(flist):
                price = l[6]
                if price == '':
                    price = Dec('0')
                else:
                    price = Dec(str(l[6]))
                tax = price * Dec(str(self.matetax))
                tax = Dec(str(float(tax)))
                temprow = [*l[2:5], '0', price, tax, price + tax, '0.0', '0.0', '0.0', '甲供', l[5], l[7]]
                flist[index] = temprow
            if len(flist) == 0:
                break
            addratedict = self.genmaterialtotal(flist)
            materialdict = dict()
            for j in self.material_type:
                temp = []
                materialdict[j] = temp

            for i in flist:
                for j in materialdict:
                    if i[12] == j:
                        materialdict[j].append(i)
            
            flist = []
            for name in self.material_type:
                if len(materialdict[name]) > 1:
                    for row in materialdict[name]:
                        flist.append(row)
                    for row in addratedict[name]:
                        flist.append(row)
            
            emtyrow = self.genseparaterow(flist)
            flist.append(emtyrow)
            flist.append(addratedict['总计'])
            
            self.fdict[tablename] = flist
        
    def InitTable5(self):
        con = Dec('0')
        equ = Dec('0')
        safebase = Dec('0')
        path = self.path

        # 处理dis 勘测距离
        if self.initflag:
            dis_pip = 0
            dis_bury = 0
            dis_common = 0
            dis_underw = 0
            dis_unders = 0
        else:
            data = self.note.GetData('表三甲')

            dis_pip = 0
            dis_bury = 0
            dis_common = 0
            dis_underw = 0
            dis_unders = 0

            for row in data:
                if row[0] in self.pip_survey_quota:
                    dis_pip += float(row[3])
                elif row[0] in self.bury_survey_quota:
                    dis_bury += float(row[3])
                elif row[0] in self.common_survey_quota:
                    dis_common += float(row[3])
                elif row[0] in self.underw_survey_quota:
                    dis_underw += float(row[3])
                elif row[0] in self.unders_survey_quota:
                    dis_unders += float(row[3])

        # 处理con 为建筑安装工程费 折扣含税价
        con = Dec(str(self.table2flist[0][3]))

        # 处理equ 为需要安装设备费
        A = copy.deepcopy(self.materA)
        B = copy.deepcopy(self.materB)
        C = copy.deepcopy(self.materC)
        tax = [self.matetax, self.contax, 0]
        for index, i in enumerate([A, B, C]):
            equ += Dec(str(i['设备'])) + Dec(str(i['设备']))*Dec(str(tax[index]))
        equ = Dec(str(round(float(equ), 2)))
        # 处理safebase 为国标建筑安装工程费(除税价)
        safebase = Dec(str(self.table2flists[1][3]))

        # 初始化table5费用生成器
        path = os.path.join(self.path, 'Survey.db')
        costs = Table5rate(self.pro, path=path, dis_pip=dis_pip,
            dis_bury=dis_bury, dis_common=dis_common,
            dis_underw=dis_underw, dis_unders=dis_unders,
            design_rate=self.discountd, supervision_rate=self.discounts,
            safe_rate=self.discountsafe, audit_rate=self.discounta,
            dis_pip_rate=self.discountss, dis_bury_rate=self.discountss, 
            dis_common_rate=self.discountss, dis_underw_rate=self.discountss, 
            dis_unders_rate=self.discountss, stage_rate=self.stage_rate,
            con=con, equ=equ, safebase=safebase)
        table5data = costs.getrate()

        self.gentable5list(table5data)

    def InitGrid(self, parent):
        self.tablestyledata=self.default_style[self.pro]
        self.note = BudgetGridNotebook(parent, *self.tablestyledata, windowname=self.windowname)
        self.note.setdata(self.fdict)
        self.note.GetHandler = self.GetHandler

        if self.initflag:
            # 表一传递函数
            self.note.getpanel('表一').Table1GetRates = self.Table1GetRates
            self.note.getpanel('表一').Table1SetRates = self.Table1SetRates
            # 表三甲传递函数
            self.note.getpanel('表三甲').AddTable3Qutoa = self.AddTable3Qutoa
            self.note.getpanel('表三甲').DelTable3Qutoas = self.DelTable3Qutoas
            self.note.getpanel('表三甲').ExportTable3Data = self.ExportTable3Data
            self.note.getpanel('表三甲').UpdateTable3Datas = self.UpdateTable3Datas
            self.note.getpanel('表三甲').DataRowUp = self.DataRowUp
            self.note.getpanel('表三甲').DataRowDown = self.DataRowDown
            self.note.getpanel('表三甲').getdatalen = self.getdatalen
            # 表三乙丙传递函数
            self.note.getpanel('表三乙').DelTable3Qutoas = self.DelTable3Qutoas
            self.note.getpanel('表三丙').DelTable3Qutoas = self.DelTable3Qutoas
            self.note.getpanel('表三乙').DataRowUp = self.DataRowUp
            self.note.getpanel('表三乙').DataRowDown = self.DataRowDown
            self.note.getpanel('表三丙').DataRowUp = self.DataRowUp
            self.note.getpanel('表三丙').DataRowDown = self.DataRowDown
            self.note.getpanel('表三乙').getdatalen = self.getdatalen
            self.note.getpanel('表三丙').getdatalen = self.getdatalen
            self.note.getpanel('表三乙').FromBCGetARows = self.FromBCGetARows
            self.note.getpanel('表三丙').FromBCGetARows = self.FromBCGetARows
            self.note.getpanel('表三乙').ExportTable3Data = self.ExportTable3Data
            self.note.getpanel('表三乙').UpdateTable3Datas = self.UpdateTable3Datas
            self.note.getpanel('表三丙').ExportTable3Data = self.ExportTable3Data
            self.note.getpanel('表三丙').UpdateTable3Datas = self.UpdateTable3Datas
            # 表四传递函数
            self.note.getpanel('表四材料').Table4AddData = self.Table4AddData
            self.note.getpanel('表四设备').Table4AddData = self.Table4AddData
            self.note.getpanel('表四材料').settable4readonly = self.settable4readonly
            self.note.getpanel('表四设备').settable4readonly = self.settable4readonly
            self.note.getpanel('表四材料').Table4DelData = self.Table4DelData
            self.note.getpanel('表四设备').Table4DelData = self.Table4DelData
            self.note.getpanel('表四材料').DataRowUp = self.DataRowUp
            self.note.getpanel('表四设备').DataRowUp = self.DataRowUp
            self.note.getpanel('表四材料').DataRowDown = self.DataRowDown
            self.note.getpanel('表四设备').DataRowDown = self.DataRowDown
            self.note.getpanel('表四材料').getdatalen = self.getdatalen
            self.note.getpanel('表四设备').getdatalen = self.getdatalen
            self.note.getpanel('表四材料').Table4ChangeData = self.Table4ChangeData
            self.note.getpanel('表四设备').Table4ChangeData = self.Table4ChangeData
            self.note.getpanel('表四材料').Table4GetRate = self.Table4GetRate
            self.note.getpanel('表四设备').Table4GetRate = self.Table4GetRate
            self.note.getpanel('表四材料').Table4SetRate = self.Table4SetRate
            self.note.getpanel('表四设备').Table4SetRate = self.Table4SetRate
            # 表五传递函数
            self.note.getpanel('表五').Table5AddData = self.Table5AddData
            self.note.getpanel('表五').Table5ChangeData = self.Table5ChangeData
            self.note.getpanel('表五').Table5GetRate = self.Table5GetRate
            self.note.getpanel('表五').Table5ChangeRate = self.Table5ChangeRate
            self.note.getpanel('表五').GetTaxs = self.GetTaxs
            self.note.getpanel('表五').DataRowUp = self.DataRowUp
            self.note.getpanel('表五').DataRowDown = self.DataRowDown
            self.note.getpanel('表五').Table5Del = self.Table5Del
            # 传递handler函数
            self.note.ExportTemplet = self.ExportTemplet
            self.note.ImportTemplet = self.ImportTemplet
            self.note.ExportData = self.ExportData
            self.note.ImportData = self.ImportData
            self.note.ExportInitData = self.ExportInitData
            self.note.ImportInitData = self.ImportInitData


        # 设置表三甲乙丙 绑定事件 设置只读列
        choicer3 = wx.grid.GridCellAttr()
        choicer3.SetEditor(wx.grid.GridCellChoiceEditor(['', '拆除入库', '拆除不入库']))
        self.table3grid = self.note.getgrid('表三甲')
        self.table3Bgrid = self.note.getgrid('表三乙')
        self.table3Cgrid = self.note.getgrid('表三丙')
        self.table3grid.SetColAttr(8,choicer3)
        self.table3grid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.OnChangeTable3)

        self.settable3readonly()
        
        # 设置表四两个 绑定事件 设置只读列
        choicer4 = wx.grid.GridCellAttr()
        choicer4.SetEditor(wx.grid.GridCellChoiceEditor(['甲供', '乙供', '利旧']))
        choicer4_1 = wx.grid.GridCellAttr()
        choicer4_1.SetEditor(wx.grid.GridCellChoiceEditor(['甲供', '乙供', '利旧']))
        self.table4Agrid = self.note.getgrid('表四设备')
        self.table4Bgrid = self.note.getgrid('表四材料')
        self.table4Agrid.SetColAttr(10,choicer4)
        self.table4Bgrid.SetColAttr(10,choicer4_1)

        self.table4Bgrid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.OnChangeTable4)
        self.table4Agrid.Bind(wx.grid.EVT_GRID_CELL_CHANGED, self.OnChangeTable4)

        self.settable4readonly()

        # 设置表二
        self.RefreshTable2()
        self.settable2readonly()

        # 设置表五
        self.RefreshTable5()
        self.settable5readonly()

        # 设置表一
        self.RefreshTable1()
        self.settable1readonly()

        self.initflag = False

    def Show(self, bool):
        self.note.Show(bool)
        self.note.Maximize(bool)

    def settable2readonly(self):
        self.table2grid.DisableDragRowSize()
        self.table2Sgrid.DisableDragRowSize()
        realcol = self.table2grid.GetNumberCols()
        realrow = self.table2grid.GetNumberRows()
        for row in range(realrow):
            for col in range(realcol):
                self.table2grid.SetReadOnly(row, col)
                self.table2Sgrid.SetReadOnly(row, col)

    def settable3readonly(self):
        self.table3grid.DisableDragRowSize()
        self.table3Bgrid.DisableDragRowSize()
        self.table3Cgrid.DisableDragRowSize()
        lastrow = 4
        realcol = self.table3grid.GetNumberCols()
        realrow = self.table3grid.GetNumberRows()
        for row, rowv in enumerate(self.fdict['表三甲']):
            for col in range(realcol):
                if row >= (len(self.fdict['表三甲']) - lastrow):
                    self.table3grid.SetReadOnly(row, col)
                else:
                    if col in [0, 1, 2, 4, 5, 6, 7, 9, 10]:
                        self.table3grid.SetReadOnly(row, col)

        lendata = len(self.fdict['表三甲'])
        if realrow > lendata:
            for row in range(lendata, realrow):
                for col in range(realcol):
                    self.table3grid.SetReadOnly(row, col)

        # ***********************************************************
        # ***********************************************************
        
        namedict = {'表三乙': self.table3Bgrid, '表三丙': self.table3Cgrid}
        for name in namedict:
            realcol = namedict[name].GetNumberCols()
            realrow = namedict[name].GetNumberRows()
            for row, rowv in enumerate(self.fdict[name]):
                for col in range(realcol):
                    namedict[name].SetReadOnly(row, col)

            lendata = len(self.fdict[name])
            if realrow > lendata:
                for row in range(lendata, realrow):
                    for col in range(realcol):
                        namedict[name].SetReadOnly(row, col)

    def settable4readonly(self):

        def isinfreez(string):
            for i in freezlist:
                if i in str(string):
                    return True
            return False
        self.table4Agrid.DisableDragRowSize()
        self.table4Bgrid.DisableDragRowSize()
        namedict = {'表四材料': self.table4Bgrid, '表四设备': self.table4Agrid}
        freezlist = ['小计', '运杂费', '保险费', '保管费',
                    '采购代理服务费(直接金额)', '合计']
        for name in namedict:
            realcol = namedict[name].GetNumberCols()
            realrow = namedict[name].GetNumberRows()
            for row, rowv in enumerate(self.note.GetData(name)):
                isempty = self.islistempty(rowv)
                for col, value in enumerate(rowv):
                    if isempty:
                        namedict[name].SetReadOnly(row, col)
                    elif isinfreez(rowv[0]) and len(rowv[0]) > 2 and rowv[0][:2] in self.material_type:
                        namedict[name].SetReadOnly(row, col)
                    elif col != 3 and col != 10:
                        namedict[name].SetReadOnly(row, col)

            lendata = len(self.note.GetData(name))
            for row in range(lendata - 3, lendata):
                for col in range(realcol):
                    namedict[name].SetReadOnly(row, col)

    def settable5readonly(self):
        self.table5grid.DisableDragRowSize()
        realcol = self.table5grid.GetNumberCols()
        realrow = self.table5grid.GetNumberRows()
        for row in range(realrow):
            for col in range(realcol):
                self.table5grid.SetReadOnly(row, col)

    def settable1readonly(self):
        self.table1grid.DisableDragRowSize()
        realcol = self.table1grid.GetNumberCols()
        realrow = self.table1grid.GetNumberRows()
        for row in range(realrow):
            for col in range(realcol):
                self.table1grid.SetReadOnly(row, col)


    def OnChangeTable3(self, event):
        eventrow = event.GetRow()
        eventcol = event.GetCol()
        datalen = len(self.note.GetData('表三甲')) - 1
        mechsum = Dec('0')
        worksum = Dec('0')
        serial = self.table3grid.GetCellValue(eventrow, 0)
        orign = self.table3grid.GetCellValue(eventrow, 11)
        value = self.table3grid.GetCellValue(eventrow, 3)
        # 判断是不是数字
        if not self.isnum(value):
            self.table3grid.SetCellValue(eventrow, 3, '0')
            return
        value = str(float(value))
        # 拆除改变
        if eventcol == 8:
            tearhan = self.table3grid.GetCellValue(eventrow, 8)
            
            if tearhan == '':
                tearrate = str(self.teardict.get(serial + '-' + orign, ['1.0', '1.0', '1.0'])[0])
            elif tearhan == '拆除入库':
                tearrate = str(self.teardict.get(serial + '-' + orign, ['1.0', '1.0', '1.0'])[1])
            else:
                tearrate = str(self.teardict.get(serial + '-' + orign, ['1.0', '1.0', '1.0'])[2])
            if tearrate == '':
                tearrate = '0.0'
            self.table3grid.SetCellValue(eventrow, 9 , tearrate)

            for index, rowv in enumerate(self.fdict['表三乙']):
                if rowv[0] == serial:
                    self.table3Bgrid.SetCellValue(index, 10, tearrate)
                    self.table3Bgrid.SetCellValue(index, 9, tearhan)

            for index, rowv in enumerate(self.fdict['表三丙']):
                if rowv[0] == serial:
                    self.table3Cgrid.SetCellValue(index, 10, tearrate)
                    self.table3Cgrid.SetCellValue(index, 9, tearhan)
        # 定额改变
        if (eventcol == 3 or eventcol == 8) and self.table3grid.GetCellValue(eventrow, 0) != '':
            if Dec(value) == 0:
                self.table3grid.SetCellValue(eventrow, 3, '0')
            else:
                self.table3grid.SetCellValue(eventrow, 3, str(float(value)))
            mechquota = self.nullorzero(self.table3grid.GetCellValue(eventrow,4))
            workquota = self.nullorzero(self.table3grid.GetCellValue(eventrow,5))
            rate = self.nullorzero(self.table3grid.GetCellValue(eventrow,9))
            if self.isnum(value):
                valuemech = Dec(mechquota) * Dec(value) * Dec(rate)
                self.table3grid.SetCellValue(eventrow, 6, str(float(valuemech)))
                valuework = Dec(workquota) * Dec(value) * Dec(rate)
                self.table3grid.SetCellValue(eventrow, 7, str(float(valuework)))
            else:
                self.table3grid.SetCellValue(eventrow, 3, '0.0')
        for row in range(datalen-3):
            mechsum += Dec(self.nullorzero(self.table3grid.GetCellValue(row,6)))
            worksum += Dec(self.nullorzero(self.table3grid.GetCellValue(row,7)))

        # 改变调整参数
        adjmech = Dec('0')
        adjwork = Dec('0')
        if self.pro == 'book4':
            if mechsum + worksum <= 100:
                rate = '0.15'
                string = '工程总工日在 100工日以下时，增加 15%'
            elif mechsum + worksum <= 250:
                rate = '0.10'
                string = '工程总工日在 100-250工日时，增加 10%'
            else:
                rate = '0.00'
                string = '无调整系数'
            if rate != '0.00':
                adjmech = mechsum*Dec(rate)
                adjwork = worksum*Dec(rate)
                self.table3grid.SetCellValue(datalen-3, 6, str(float(adjmech)))
                self.table3grid.SetCellValue(datalen-3, 7, str(float(adjwork)))
            else:
                self.table3grid.SetCellValue(datalen-3, 6, '')
                self.table3grid.SetCellValue(datalen-3, 7, '')
            self.table3grid.SetCellValue(datalen-3, 1, string)
        # 改变特殊区域调整系数
        spicmach = Dec('0')
        spicwork = Dec('0')
        if self.table3_specarea_rate != 0:
            spicmach = mechsum*Dec(str(self.table3_specarea_rate))
            spicwork = worksum*Dec(str(self.table3_specarea_rate))
            self.table3grid.SetCellValue(datalen-2, 6, str(float(spicmach)))
            self.table3grid.SetCellValue(datalen-2, 7, str(float(spicwork)))
            
        # 改变合计
        self.table3grid.SetCellValue(datalen-1, 6, str(float(mechsum+adjmech+spicmach)))
        self.table3grid.SetCellValue(datalen-1, 7, str(float(worksum+adjwork+spicwork)))

        # **************************************
        # 写入表二需要参数
        self.mech = float(mechsum+adjmech+spicmach)
        self.work = float(worksum+adjwork+spicwork)
        # **************************************

        # 改变表三乙丙
        namedict = {'表三乙': self.table3Bgrid, '表三丙': self.table3Cgrid}
        # table2namedict = {'表三乙': self.mach, '表三丙': self.meter}
        hasflag = False
        for name in namedict:
            for index, rowv in enumerate(self.note.GetData(name)):
                if rowv[0] == serial and rowv[-2] == orign and rowv[-1] == '1':
                    hasflag = True
                    namedict[name].SetCellValue(index, 3, value)
                    tablelen = len(self.note.GetData(name)) - 1 
                    sumprice = Dec('0')

                    # 当行改变
                    rate = Dec(namedict[name].GetCellValue(index, 10))
                    num = Dec(namedict[name].GetCellValue(index, 3))
                    pcon = Dec(namedict[name].GetCellValue(index, 5))
                    con = num * pcon
                    pprice = Dec(namedict[name].GetCellValue(index, 6))
                    price = pprice * con * rate
                    namedict[name].SetCellValue(index, 7, str(float(con)))
                    namedict[name].SetCellValue(index, 8, str(float(price)))
            if hasflag:
                hasflag = False
                specadj = Dec('0')
                for row in range(tablelen-2):
                    sumprice += Dec(self.nullorzero(namedict[name].GetCellValue(row,8)))
                if name == '表三乙':
                    specadj = sumprice * Dec(str(self.table3_specarea_rate))
                    namedict[name].SetCellValue(tablelen-2, 8, str(float(specadj)))
                # 改变合计
                namedict[name].SetCellValue(tablelen-1, 8, str(float(sumprice+specadj)))

                # *************************************************
                # 写入表二需要数据
                # table2namedict[name] = float(sumprice+specadj)
                if name == '表三乙':
                    self.mach = float(sumprice+specadj)
                elif name == '表三丙':
                    self.meter = float(sumprice+specadj)
                # *************************************************
        # 更新表二数据
        self.InitTable2()
        self.RefreshTable2()
        # 更新表五数据
        self.InitTable5()
        self.RefreshTable5()
        # 更新表一数据
        self.InitTable1()
        self.RefreshTable1()
        # print('table3', self.mech, self.work, self.mach, self.meter)

    def OnChangeTable4(self, event):
        tablename = event.GetEventObject().name
        objdict = {'表四材料': self.table4Bgrid, '表四设备': self.table4Agrid}
        eventrow = event.GetRow()
        eventcol = event.GetCol()

        data = self.note.GetData(tablename)
        if data[0][:4] == ['', '', '', '']:
            return

        datalen = len(self.note.GetData(tablename))
        value = objdict[tablename].GetCellValue(eventrow, 3)
        price = Dec(objdict[tablename].GetCellValue(eventrow, 4))
        tax = Dec(objdict[tablename].GetCellValue(eventrow, 5))
        tprice = Dec(objdict[tablename].GetCellValue(eventrow, 6))
        rate = Dec(objdict[tablename].GetCellValue(eventrow, 11))
        Atax = Dec(str(self.matetax))
        Btax = Dec(str(self.contax))
        # 判断输入是不是数字
        if not self.isnum(value):
            objdict[tablename].SetCellValue(eventrow, 3, '0')
            return
        value = Dec(value)
        # 供应方发生改变 改变税率及含税价
        if eventcol == 10:
            temp = objdict[tablename].GetCellValue(eventrow, 10)
            if temp == '甲供':
                tax = round(Dec(price) * Atax, 2)
            elif temp == '乙供':
                tax = round(Dec(price) * Btax, 2)
            else:
                tax = round(Dec(price) * Dec('0'), 2)
            tprice = tax + price
            objdict[tablename].SetCellValue(eventrow, 5, str(tax))
            objdict[tablename].SetCellValue(eventrow, 6, str(tprice))
        # 数量或供应方发生改变 改变大小
        if eventcol == 3 or eventcol == 10:
            if value == 0:
                objdict[tablename].SetCellValue(eventrow, 3, '0')
            else:
                objdict[tablename].SetCellValue(eventrow, 3, str(float(value)))
            totalprice = value * price * rate
            totaltax = value * tax * rate
            totaltprice = value * tprice * rate
            objdict[tablename].SetCellValue(eventrow, 7, str(float(totalprice)))
            objdict[tablename].SetCellValue(eventrow, 8, str(float(totaltax)))
            objdict[tablename].SetCellValue(eventrow, 9, str(float(totaltprice)))
        # 数量或供应方发生改变 改变合计
            # **************************
            # 收集表二需要的数据
            thistype = objdict[tablename].GetCellValue(eventrow, 12)
            self.materA[thistype] = Dec('0')
            self.materB[thistype] = Dec('0')
            self.materC[thistype] = Dec('0')
            # **************************
            startrow = self.findstartrow(self.note.GetData(tablename), eventrow)
            stotalrow = self.findsubtotalrow(self.note.GetData(tablename), eventrow)
            # 小计数据
            stotalprice = Dec('0.0')
            stotaltax = Dec('0.0')
            stotaltprice = Dec('0.0')
            # 运杂费
            transrate = Dec(objdict[tablename].GetCellValue(stotalrow + 1, 11))
            transprice = Dec('0.0')
            transtax = Dec('0.0')
            transtprice = Dec('0.0')
            # 保险费
            insurrate = Dec(objdict[tablename].GetCellValue(stotalrow + 2, 11))
            insurprice = Dec('0.0')
            insurtax = Dec('0.0')
            insurtprice = Dec('0.0')
            
            # 采购及保管费
            storrate = Dec(objdict[tablename].GetCellValue(stotalrow + 3, 11))
            storprice = Dec('0.0')
            stortax = Dec('0.0')
            stortprice = Dec('0.0')

            for row in range(startrow, stotalrow):
                rowprice = Dec(objdict[tablename].GetCellValue(row, 7))
                rowtax = Dec(objdict[tablename].GetCellValue(row, 8))
                rowtprice = Dec(objdict[tablename].GetCellValue(row, 9))
                stotalprice += rowprice
                stotaltax += rowtax
                stotaltprice += rowtprice
                if rowprice != 0:
                    if objdict[tablename].GetCellValue(row, 10) == '甲供':
                        transprice += rowprice * transrate
                        insurprice += rowprice * insurrate
                        transtax += rowprice * Dec(str(self.matetax)) * transrate
                        insurtax += rowprice * Dec(str(self.matetax)) * insurrate
                        # **************************
                        # 收集表二需要的数据
                        self.materA[thistype] += rowprice + rowprice * transrate + rowprice * insurrate
                        self.materB[thistype] += rowprice * storrate
                        # **************************
                    elif objdict[tablename].GetCellValue(row, 10) == '乙供':
                        transprice += rowprice * transrate
                        insurprice += rowprice * insurrate
                        transtax += rowprice * Dec(str(self.contax)) * transrate
                        insurtax += rowprice * Dec(str(self.contax)) * insurrate
                        # **************************
                        # 收集表二需要的数据
                        self.materB[thistype] += rowprice + rowprice * transrate + rowprice * insurrate + rowprice * storrate
                        # **************************
                    else:
                        # **************************
                        # 收集表二需要的数据
                        self.materC[thistype] += rowprice + rowprice * storrate
                        self.materB[thistype] += rowprice * storrate
                        # **************************

            transtprice = transprice + transtax
            insurtprice = insurprice + insurtax
            storprice = stotalprice * storrate
            stortax = storprice * Dec(str(self.contax))
            stortprice = storprice + stortax

            setlist = [
                        [stotalprice, stotaltax, stotaltprice],
                        [transprice, transtax, transtprice],
                        [insurprice, insurtax, insurtprice],
                        [storprice, stortax, stortprice],
                        ]

            for row in range(4):
                if Dec(objdict[tablename].GetCellValue(stotalrow + row, 11)) == 0:
                    for col in range(7, 10):
                        objdict[tablename].SetCellValue(stotalrow + row, col, str(float('0.0')))
                else:
                    for col in range(7, 10):
                        objdict[tablename].SetCellValue(stotalrow + row, col, str(float(setlist[row][col-7])))
            # 合计
            totalrow = stotalrow + 5
            totalprice = Dec('0.0')
            totaltax = Dec('0.0')
            totaltprice = Dec('0.0')
            for row in range(stotalrow, totalrow):
                temp1 = objdict[tablename].GetCellValue(row, 7)
                temp2 = objdict[tablename].GetCellValue(row, 8)
                temp3 = objdict[tablename].GetCellValue(row, 9)
                if self.isnum(temp1):
                    totalprice += Dec(temp1)
                if self.isnum(temp2):
                    totaltax += Dec(temp2)
                if self.isnum(temp3):
                    totaltprice += Dec(temp3)

            objdict[tablename].SetCellValue(totalrow, 7, str(float(totalprice)))
            objdict[tablename].SetCellValue(totalrow, 8, str(float(totaltax)))
            objdict[tablename].SetCellValue(totalrow, 9, str(float(totaltprice)))

            rowlist = self.findtotalrows(self.note.GetData(tablename))
            ttotalprice = Dec('0')
            ttotaltax = Dec('0')
            ttotaltprice = Dec('0')
            for row in rowlist:
                totalprice = objdict[tablename].GetCellValue(row, 7)
                totaltax = objdict[tablename].GetCellValue(row, 8)
                totaltprice = objdict[tablename].GetCellValue(row, 9)
                if self.isnum(totalprice):
                    ttotalprice += Dec(totalprice)
                if self.isnum(totaltax):
                    ttotaltax += Dec(totaltax)
                if self.isnum(totaltprice):
                    ttotaltprice += Dec(totaltprice)

            ttotalprice = round(float(ttotalprice), 2)
            ttotaltax = round(float(ttotaltax), 2)
            ttotaltprice = Dec(str(ttotalprice)) + Dec(str(ttotaltax))

            sumrow = ['总计', '', '', '', '', '', '',]
            sumrownum = -1
            for index, row in enumerate(self.note.GetData(tablename)):
                if row[:7] == sumrow:
                    sumrownum = index
                    break
            if sumrownum < 0:
                sumrownum = datalen
            objdict[tablename].SetCellValue(sumrownum, 7, str(ttotalprice))
            objdict[tablename].SetCellValue(sumrownum, 8, str(ttotaltax))
            objdict[tablename].SetCellValue(sumrownum, 9, str(ttotaltprice))

        # 更新表二数据
        self.InitTable2()
        self.RefreshTable2()
        # 更新表五数据
        self.InitTable5()
        self.RefreshTable5()
        # 更新表一数据
        self.InitTable1()
        self.RefreshTable1()
        # print('table4', '\n', self.materA, '\n', self.materB, '\n', self.materC, )
        

    def RefreshTable2(self):
        self.table2Sgrid = self.note.getgrid('表二（标）')
        self.table2grid = self.note.getgrid('表二')
        # *************************************************
        # 传递给GUIBudgetGrid
        if self.initflag:
            # *************************************
            # 传递方法给budgetgrid
            self.note.getpanel('表二（标）').refreshtable2 = self.RefreshTable2
            self.note.getpanel('表二（标）').initiable2 = self.InitTable2
            self.note.getpanel('表二（标）').PostTable3ChangeEvent = self.PostTable3ChangeEvent
            self.note.getpanel('表二').refreshtable2 = self.RefreshTable2
            self.note.getpanel('表二').initiable2 = self.InitTable2
            self.note.getpanel('表二').PostTable3ChangeEvent = self.PostTable3ChangeEvent
            # *************************************
            self.note.getpanel('表二（标）').ratedata = self.table2rate
            self.note.getpanel('表二（标）').discount = self.discount
            self.note.getpanel('表二（标）').discounts = self.discounts
            self.note.getpanel('表二（标）').discountd = self.discountd
            self.note.getpanel('表二（标）').contax = self.contax
            self.note.getpanel('表二（标）').matetax = self.matetax
            self.note.getpanel('表二（标）').servtax = self.servtax
            self.note.getpanel('表二（标）').ratedisc = self.table2ratedisc
            self.note.getpanel('表二').ratedata = self.table2rate
            self.note.getpanel('表二').discount = self.discount
            self.note.getpanel('表二').contax = self.contax
            self.note.getpanel('表二').matetax = self.matetax
            self.note.getpanel('表二').servtax = self.servtax
            self.note.getpanel('表二').ratedisc = self.table2ratedisc
            self.note.getpanel('表二').ratedisable = self.table2disable
            self.note.getpanel('表二').ton = self.ton
            self.note.getpanel('表二').mach_dis = self.mach_dis
            self.note.getpanel('表二').sc2en_dis = self.sc2en_dis
        else:
            self.table2rate = self.note.getpanel('表二（标）').ratedata
            self.table2ratedisc = self.note.getpanel('表二（标）').ratedisc
            self.table2rate = self.note.getpanel('表二').ratedata
            self.table2ratedisc = self.note.getpanel('表二').ratedisc
            self.discount = self.note.getpanel('表二').discount 
            self.contax = self.note.getpanel('表二').contax 
            self.matetax = self.note.getpanel('表二').matetax 
            self.servtax = self.note.getpanel('表二').servtax 
            self.table2disable = self.note.getpanel('表二').ratedisable 
            self.ton = self.note.getpanel('表二').ton
            self.mach_dis = self.note.getpanel('表二').mach_dis
            self.sc2en_dis = self.note.getpanel('表二').sc2en_dis
        # *************************************************
        self.setcelldata(self.table2flists, self.table2Sgrid)
        self.setcelldata(self.table2flist, self.table2grid)

    def PostTable3ChangeEvent(self, row=0, col=3):
        table3id = self.table3grid.GetId()
        eventtype = wx.grid.EVT_GRID_CELL_CHANGED.typeId
        event = wx.grid.GridEvent(table3id, eventtype,
            self.table3grid, row=row, col=col)
        wx.PostEvent(self.table3grid, event)

    def PostTable4ChangeEvent(self, row=0, col=3, name='表四材料'):
        grid = self.note.getgrid(name)
        table4id = grid.GetId()
        eventtype = wx.grid.EVT_GRID_CELL_CHANGED.typeId
        event = wx.grid.GridEvent(table4id, eventtype,
            grid, row=row, col=col)
        wx.PostEvent(grid, event)

    def RefreshTable5(self):
        self.table5grid = self.note.getgrid('表五')

        self.setcelldata(self.table5flist, self.table5grid)

    def RefreshTable1(self):
        self.table1grid = self.note.getgrid('表一')
        self.setcelldata(self.table1flist, self.table1grid)

    def isnum(self, string):
        try:
            if string=='NaN':
                return False
            float(string)
            return True
        except ValueError:
            return False

    def nullorzero(self, string):
        if string == '':
            return '0.0'
        else:
            return string

    def findsubtotalrow(self, data, startrow):
        # 表四找到小计那一行
        for row, rowv in enumerate(data[startrow: ]):
            if rowv[0][:2] in self.material_type and rowv[0][-2:] == '小计':
                return row + startrow

    def findstartrow(self, data, startrow):
        # 表四找到第一行
        tempdata = data[:startrow]
        tempdata.reverse()
        for row, rowv in enumerate(tempdata):
            if rowv[0][:2] in self.material_type and rowv[0][-2:] == '合计':
                return startrow - row 
        return 0

    def findtotalrows(self, data):
        # 表四找到所有合计那行
        relist = []
        for row, rowv in enumerate(data):
            if rowv[0][:2] in self.material_type and rowv[0][-2:] == '合计':
                relist.append(row)
        return relist



    def changtable3adjust(self, isit):
        # 是否在表三添加调整系数
        if isit:
            self.table3adjust = 1
        else:
            return

    def gentable5list(self, data):
        if self.initflag:
            self.table5flist = [
                        ['建设用地及综合赔补费'],
                        ['建设单位管理费'],
                        ['可行性研究费'],
                        ['研究试验费'],
                        ['勘察设计费'],
                        ['勘察费'],
                        ['设计费'],
                        ['环境影响评价费'],
                        ['劳动安全卫生评价费'],
                        ['建设工程监理费'],
                        ['安全生产费'],
                        ['引进技术及引进设备其它费'],
                        ['工程保险费'],
                        ['工程招标代理费'],
                        ['专利及专利技术使用费'],
                        ['审计费'],
                        ['总计'],
                        ]
                        
        tprice = Dec('0')
        ttax = Dec('0')
        for index, row in enumerate(self.table5flist):
            taxrate = self.servtax
            if row[0] in data:
                self.table5flist[index] = [row[0]]
                formula = '(' + data[row[0]] + ')/' + str(1+self.servtax)
                if row[0] == '安全生产费':
                    formula = data[row[0]]
                self.table5flist[index].append(formula)
                price = self.table2parseformula(formula)
                price = self.listadddec(price)
                price = self.list2str(price)
                price = Dec(str(float(eval(price))))
                price = round(price, 2)
                tprice += price
                if row[0] == '安全生产费':
                    taxrate = self.contax
                tax = Dec(str(price)) * Dec(str(taxrate))
                tax = Dec(str(float(tax)))
                tax = round(tax, 2)
                ttax += tax
                self.table5flist[index].append(price)
                self.table5flist[index].append(tax)
                self.table5flist[index].append(price + tax)
            elif row[0] == '总计':
                self.table5flist[index] = [row[0]]
                self.table5flist[index].append('')
                self.table5flist[index].append(tprice)
                self.table5flist[index].append(ttax)
                self.table5flist[index].append(tprice + ttax)
            elif row[0] == '勘察设计费':
                self.table5flist[index] = [row[0]]
                s = data.get('勘察费', '0.0')
                d = data.get('设计费', '0.0')
                s, d = '(' + s + ')/' + str(1+self.servtax), '(' + d + ')/' + str(1+self.servtax)
                pricestr = s + '+' + d
                price1, price2 = self.table2parseformula(s), self.table2parseformula(d)
                price1, price2 = self.listadddec(price1), self.listadddec(price2)
                price1, price2 = self.list2str(price1), self.list2str(price2)
                price1, price2 = Dec(str(float(eval(price1)))), Dec(str(float(eval(price2))))
                tax1, tax2 = Dec(str(price1)) * Dec(str(taxrate)), Dec(str(price2)) * Dec(str(taxrate))
                tax1, tax2 = Dec(str(float(tax1))), Dec(str(float(tax2)))
                price = round(price1,2) + round(price2,2)
                tax = round(tax1,2) + round(tax2,2)
                self.table5flist[index].append(pricestr)
                self.table5flist[index].append(price)
                self.table5flist[index].append(tax)
                self.table5flist[index].append(price + tax)
            else:
                try:
                    price = Dec(row[2])
                    tax = Dec(row[3])
                    tprice += price
                    ttax += tax
                except IndexError:
                    pass

    def gentable3adjustrow(self, data):
        # 添加调整系数行
        # args为有调整系数的列
        lencol = len(data[0])
        relist = ['', '无规模调整系数']

        for i in range(lencol-2):
            relist.append('')

        return relist

    def gentable3sumrow(self, data):
        # 添加合计行

        lencol = len(data[0])
        relist = ['', '合计']
        for i in range(lencol-2):
            relist.append('')

        # relist[6] = '@SUM(0,6):(' + str(lenrow-1) + ',6)'
        # relist[7] = '@SUM(0,7):(' + str(lenrow-1) + ',7)'

        return relist

    def genmaterialtotal(self, data):
        # 生成小计运杂费等
        # data 为表四 fdict 获取长度
        # name 为材料类型名字
        table4rate = Table4rate(self.pro, self.mat_dis, path=os.path.join(self.path, 'rate.db'))
        ratedict = table4rate.getrate()
        redict = dict()
        collist = ['%s小计', '%s运杂费：费率%.2f%%', '%s运输保险费：费率%.2f%%', 
                   '%s采购保管费：费率%.2f%%', '%s采购代理服务费(直接金额)', '%s合计']
        namelist = ['运杂费', '运保费', '采购及保管费']

        for name in self.material_type:
            tempout = []
            for index, row in enumerate(collist):
                temp = ['' for i in data[0]]
                if index == 4 or index == 0 or index == 5:
                    temp[0] = row%name
                    temp[11] = '1'
                else:
                    rate = ratedict[name + namelist[index-1]]
                    temp[0] = row%(name, rate)
                    temp[11] = Dec(str(rate)) / Dec('100')
                tempout.append(temp)
            redict[name] = tempout
        
        temp = ['' for i in data[0]]
        temp[0] = '总计'
        redict['总计'] = temp

        return redict

    def genspicaerarow(self, data):
        # 生成表三乙丙特殊区域调整系数
        datalen = len(data[0])
        temp = ['' for i in range(datalen)]
        disrate = Dec(str(self.table3_specarea_rate))*Dec('100.0')
        temp[1] = '特殊区域调整系数（%s, %s%%）'%(self.table3_specarea, str(float(disrate)))
        return temp

    def getmafeerate(self, name):
        # 获取材料运杂费等费率
        pass

    def listdeler(self, l, col, keyword):
        # l 为 [[...],[...]] 格式
        # col 为匹配列
        # keyword 为匹配字符串 匹配成功删除 小list
        dellist = []
        for index, value in enumerate(l):
            if value[col] != keyword:
                dellist.append(index)

        dellist.reverse()
        for i in dellist:
            l.pop(i)
        return l

    def genseparaterow(self, data):
        # 生成空数据行
        row = ['' for i in data[0]]
        return row

    def genseralnum(self, level, num):
        hanlist = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
        num -= 1
        if level == 1:
            try:
                return hanlist[num]
            except IndexError:
                return '数字太大请修改FrontDataHandler.genseralnum函数'
        elif level == 2:
            try:
                return '(' + hanlist[num] + ')'
            except IndexError:
                return '数字太大请修改FrontDataHandler.genseralnum函数'
        elif level == 3:
            return str(num+1)
        elif level == 4:
            return '(' + str(num+1) + ')'
        elif level == 0:
            return ''
        else:
            return '层级太大请修改FrontDataHandler.genseralnum函数'

    def table2datadeal(self, rate, disc, filldict, dfilldict, discount, roundnum=2):
        
        initdata = self.geninitdata(discount)
        outsidecost = ['大型施工机械调遣费', '施工队伍调遣费', ]
        lastcost = ['建筑安装工程费(含税价)', '建筑安装工程费(除税价)']
        for name in rate:
            if name in lastcost:
                continue
            if isinstance(rate[name], dict):
                self.table2datadeal(rate[name], disc, filldict, dfilldict, discount, roundnum)
            else:
                thisrate = self.recursionsearch(rate, name)
                thisformula = ''

                if name in initdata:
                    filldata = Dec(str(float(initdata[name])))
                    filldata = round(filldata, roundnum)
                    self.feefillin(filldict, name, filldata)
                    self.feefillin(dfilldict, name, '')

                for row in disc:
                    if row[1] == name:
                        thisformula = self.table2parseformula(row[2])
                        thisformate = row[3]
                if name in outsidecost:
                    # if name == outsidecost[0]:
                    #     filldata = Dec(str(float(self.steam)))
                    #     dfilldata = thisformate

                    # elif name == outsidecost[1]:
                    #     filldata = Dec(str(float(self.earth_dis))) * Dec(str(float(thisrate)))
                    #     dfilldata = thisformate%(self.earth_dis, thisrate)
                    
                    if name == outsidecost[0]:
                        filldata = Dec(str(float(thisrate[1]))) * Dec(str(float(thisrate[0]))) * Dec('2')
                        dfilldata = thisformate%(thisrate[0], thisrate[1])
                    
                    # elif name == outsidecost[3]:
                    #     filldata = Dec(str(float(self.sewage)))
                    #     dfilldata = thisformate
                    
                    elif name == outsidecost[1]:
                        filldata = Dec(str(float(thisrate[0]))) * Dec(str(float(thisrate[1]))) * Dec('2')
                        dfilldata = thisformate%(thisrate[0], thisrate[1])
                    filldata = Dec(str(float(filldata)))
                    filldata = round(filldata, roundnum)
                    self.feefillin(filldict, name, filldata)
                    self.feefillin(dfilldict, name, dfilldata)
                
                spec = ['工程排污费', '运土费', '施工用水电蒸汽费']
                if name in spec or thisformula != '' and name not in outsidecost:
                    for index, value in enumerate(thisformula):
                        if len(value) > 1:
                            if value in initdata:
                                thisformula[index] = initdata[value]
                            elif value == '费率':
                                if name not in ['技工费', '普工费']:
                                    thisrate = Dec(str(thisrate)) / Dec('100')
                                thisformula[index] = thisrate
                            elif self.isnum(value):
                                pass
                            else:
                                temp = self.recursionsearch(filldict, value)
                                if temp is None:
                                    temp = 0
                                if isinstance(temp, dict):
                                    temp = self.sum_dict(temp)
                                thisformula[index] = temp
                    
                    if '费率' in thisformate or '元/工日' in thisformate:
                        temprate = thisrate
                        if name not in ['技工费', '普工费']:
                            temprate = thisrate*100
                        dfilldata = thisformate%(temprate)
                    elif '一+二+三' in thisformate:
                        dfilldata = thisformate%(Dec(str(self.contax))*Dec('100'))
                    elif '特殊地区补贴金额' in thisformate:
                        dfilldata = thisformate
                    else:
                        try:
                            dfilldata = thisformate%self.discount
                        except TypeError:
                            dfilldata = thisformate

                    thisformula = self.listadddec(thisformula)
                    thisformula = self.list2str(thisformula)
                    if thisformula != '':
                        filldata = eval(thisformula)
                        filldata = Dec(str(float(filldata)))
                        filldata = round(filldata, roundnum)
                    else:
                        filldata = '0.00'
                    self.feefillin(filldict, name, filldata)
                    self.feefillin(dfilldict, name, dfilldata)

        for i in lastcost:
            for row in disc:
                if row[1] == i:
                    thisformula = self.table2parseformula(row[2])
                    thisformate = row[3]
            for index, value in enumerate(thisformula):
                if len(value) > 1:
                    if value == '销项税额' and '销项税额(折后)' in filldict['orgin']:
                        value = '销项税额(折后)'
                    if value in initdata:
                        thisformula[index] = initdata[value]
                    else:
                        temp = self.recursionsearch(filldict, value)
                        if temp is None:
                            temp = 0
                        if isinstance(temp, dict):
                            temp = self.sum_dict(temp)
                        thisformula[index] = temp
            
            dfilldata = thisformate%discount
            thisformula = self.listadddec(thisformula)
            thisformula = self.list2str(thisformula)
            
            filldata = eval(thisformula)
            filldata = Dec(str(round(float(filldata), roundnum)))

            self.feefillin(filldict, i, filldata)
            self.feefillin(dfilldict, i, dfilldata)
    
    def geninitdata(self, discount):
        # 生成table2datadeal需要的initdata
        mainmater = 0
        A = copy.deepcopy(self.materA)
        B = copy.deepcopy(self.materB)
        C = copy.deepcopy(self.materC)
        for i in [A, B, C]:
            i.pop('设备')
            mainmater += self.sum_dict(i)
        mainmater = round(mainmater, 2)

        A = copy.deepcopy(self.materA)
        A.pop('设备')
        mainmaterAtax = self.sum_dict(A) * Dec(str(self.matetax))
        mainmaterAtax = round(mainmaterAtax, 2)

        B = copy.deepcopy(self.materB)
        B.pop('设备')
        mainmaterAprice = self.sum_dict(B)

        self.mach = round(self.mach, 2)
        self.meter = round(self.meter, 2)
        initdata = {'技工工日': self.mech, '普工工日': self.work,
                    '机械使用费': self.mach, '仪表使用费': self.meter,
                    '主要材料费': mainmater,
                    '乙供主要材料费_除税价': mainmaterAprice, 
                    '甲供主要材料费_增值税': mainmaterAtax,
                    '施工单位增值税': Dec(str(self.contax)),
                    '折扣': Dec(str(discount))/Dec('100')}
        return initdata

    def listadddec(self, thislist):
        # 在formulalist 中的数字套上decimal
        sign = '()+-*/'
        for index, i in enumerate(thislist):
            i = str(i)
            if i not in sign:
                thislist[index] = 'Dec("' + str(float(i)) + '")'
        return thislist
    
    def list2str(self, thislist):
        
        if not isinstance(thislist, list):
            return ''
        restr = ''
        for i in thislist:
            if not isinstance(i,str):
                i = str(i)
            restr += i
        return restr
    
    def dictdeepserial(self, d, key, num=0, deep=-1):
        deep += 1
        for i in d:
            num += 1
            if isinstance(d[i], dict):
                if i == key:
                    return (deep, num)
                ret = self.dictdeepserial(d[i], key, 0, deep)
                if ret is not None:
                    return ret
            else:
                if i == key:
                    return (deep, num)

    def dict2list(self, data, disc, l=[]):
        for key in data:
            if isinstance(data[key], dict):
                temp = []
                temp.append(self.genseralnum(*self.dictdeepserial(disc, key)))
                temp.append(key)
                string = ''
                for i in data[key]:
                    if i == list(data[key].keys())[0]:
                        string += self.genseralnum(*self.dictdeepserial(disc, i))
                    else:
                        string = string + ' + ' + self.genseralnum(*self.dictdeepserial(disc, i))
                temp.append(string)
                temp.append(self.sum_dict(data[key]))
                l.append(temp)
                self.dict2list(data[key], disc, l)
            else:
                temp = []
                temp.append(self.genseralnum(*self.dictdeepserial(disc, key)))
                temp.append(key)
                temp.append(self.recursionsearch(disc, key))
                temp.append(self.recursionsearch(data, key))
                l.append(temp)
        return l

    def sepratetable2list(self, l):
        l.pop(2)
        lenl = len(l)
        relen = lenl // 2
        if lenl % 2 == 1:
            for index, i in enumerate(l):
                if i[0] == '二':
                    break
            l.insert(index, ['', '', '', ''])
            relen += 1
        relist = []
        for index,i in enumerate(l[:relen]):
            relist.append([*l[:relen][index], *l[relen:][index]])
        return relist
        

    def table2parseformula(self, formula):
        # 将公式字符串转换为列表（数据和符号分开）
        sign = '()+-*/'
        temp = ''
        forlist = []
        if formula == '':
            return ''
        for index, lastword in enumerate(formula):
            if lastword not in sign:
                temp += lastword                
            else:
                if temp != '':
                    forlist.append(temp)
                    temp = ''
                if index != len(formula) - 1:
                    forlist.append(lastword)
            if index == len(formula) - 1:
                if temp != '':
                    forlist.append(temp)
                    temp = ''
                else:
                    forlist.append(lastword)
        return forlist


    def recursionsearch(self, targetdict, serchkey):
        # 在targetdict 中寻找key为serchkey 的value并返回
        for k,v in targetdict.items():
            if k == serchkey:
                return v
            elif isinstance(v, dict):
                ret = self.recursionsearch(v, serchkey)
                if ret is not None:
                    return ret

    def feefillin(self, datadict, name, value):
        # 把 value写入key为name的datadict
        for i in datadict:
            if not isinstance(datadict[i], dict):
                if i == name:
                    datadict[i] = value
            else:
                self.feefillin(datadict[i], name, value)

    def feefillinall(self, datadict, value):
        # 把 value覆盖datadict的所有值
        for i in datadict:
            if not isinstance(datadict[i], dict):
                datadict[i] = value
            else:
                self.feefillinall(datadict[i], value)

    def sum_dict(self, d):
        num = Dec('0')
        if isinstance(d, dict):
            for i in d:
                if isinstance(d[i], dict):
                    num += Dec(str(self.sum_dict(d[i])))
                else:
                    if not isinstance(d[i], list):
                        if d[i] == '':
                            d[i] = 0
                        num += Dec(str(d[i]))
        else:
            num = Dec(str(d))
        return num

    def setcelldata(self, data, grid):
        rowgrid = grid.GetNumberRows()
        colgrid = grid.GetNumberCols()
        for row, rowv in enumerate(data):
            for col, value in enumerate(rowv):
                if not isinstance(value, str):
                    value = str(value)
                grid.SetCellValue(row, col, value)
        if rowgrid > row:
            for row in range(row+1, rowgrid):
                for col in range(colgrid):
                    grid.SetCellValue(row, col, '')

    def AddTable3Qutoa(self, data, row):
        # data为{'表三甲':[], '表三乙':[], '表三丙':[], }字典
        # self.teardict
        for name in ['表三甲', '表三乙', '表三丙']:
            thisdata = copy.deepcopy(self.note.GetData(name))
            thislen = self.Listlen(thisdata)
            if thislen <= row:
                    row = thislen
            wdata = data[name]
            if name == '表三甲':
                biggestnum = self.getbiggestnum(thisdata) + 1
                insertrow = row
                for i in wdata:
                    idnum = str(biggestnum + int(i[8]))
                    self.teardict[i[0] + '-' + idnum] = [*i[5: 8]]
                    temprow = [*i[0:3], '0', str(i[3]), str(i[4]), '0.0', '0.0', '', str(i[5]), '', idnum]
                    thisdata.insert(insertrow, temprow)
                    insertrow += 1
                self.table3grid.InsertRows(row, len(wdata))
                self.note.SetData(thisdata, name)
                
            else:
                insertrow = thislen
                for i in wdata:
                    idnum = str(biggestnum + int(i[7]))
                    tear = self.teardict.get(i[1] + '-' + idnum, '1.0')[0]
                    if i[0] == '':
                        isrelated = '1'
                    else:
                        isrelated = '0'
                    temprow = [*i[1:4], '0', str(i[4]), str(i[5]), str(i[6]), '0.0', '0.0',
                               '', tear, idnum, isrelated]
                    thisdata.insert(insertrow, temprow)
                    insertrow += 1
                if name == '表三乙':
                    self.table3Bgrid.InsertRows(row, len(wdata))
                else:
                    self.table3Cgrid.InsertRows(row, len(wdata))
                self.note.SetData(thisdata, name)
    
    def DelTable3Qutoas(self, rows):
        rows.reverse()
        for row in rows:
            self.DelTable3Qutoa(row)
        table3id = self.table3grid.GetId()
        eventtype = wx.grid.EVT_GRID_CELL_CHANGED.typeId
        event = wx.grid.GridEvent(table3id, eventtype,
            self.table3grid, row=0, col=3)
        wx.PostEvent(self.table3grid, event)
        
    def DelTable3Qutoa(self, row):
        serial = self.table3grid.GetCellValue(row, 0)
        idnum = self.table3grid.GetCellValue(row, 11)
        self.note.getgrid('表三甲').DeleteRows(row)
        if serial != '':
            for name in ['表三乙', '表三丙']:
                dellist = []
                for row, rowv in enumerate(self.note.GetData(name)):
                    if rowv[0] == serial and rowv[11] == idnum:
                        dellist.append(row)
                dellist.reverse()
                for i in dellist:
                    self.note.getgrid(name).DeleteRows(i)

    def ExportTable3Data(self, row):
        data = self.note.GetData('表三甲')
        thisdata = data[row]
        serial = thisdata[0]
        idnum = thisdata[11]
        redict = {'表三甲': [], '表三乙': [], '表三丙': []}
        rowdict = {'表三甲': [], '表三乙': [], '表三丙': []}
        redict['表三甲'] = [thisdata]
        rowdict['表三甲'] = [row]
        teardict = self.teardict[serial + '-' + idnum]
        bcdict = self.GetBCData(serial, idnum)
        redict.update(bcdict[0])
        rowdict.update(bcdict[1])

        return copy.copy([redict, rowdict, teardict])

    def UpdateTable3Datas(self, datas):
        # 输入datas 为ExportTable3Data返回形成的list
        for data in datas:
            redict = data[0]
            rowdict = data[1]
            teardict = data[2]
            thisdata = redict['表三甲'] 
            serial = thisdata[0][0]
            idnum = thisdata[0][11]
            teardict = [float(i) for i in teardict]
            self.teardict[serial + '-' + idnum] = teardict
            gridlist = [self.table3grid, self.table3Bgrid, self.table3Cgrid]
            for index, name in enumerate(redict):
                for rowindex, row in enumerate(rowdict[name]):
                    for col, value in enumerate(redict[name][rowindex]):
                        gridlist[index].SetCellValue(row, col, str(value))

            table3id = self.table3grid.GetId()
            eventtype = wx.grid.EVT_GRID_CELL_CHANGED.typeId
            event = wx.grid.GridEvent(table3id, eventtype,
                self.table3grid, row=rowdict['表三甲'][0], col=8)
            wx.PostEvent(self.table3grid, event)


    def GetBCData(self, serial, idnum):
        dataB = self.note.GetData('表三乙')
        dataC = self.note.GetData('表三丙')
        redict = {'表三乙': [], '表三丙': []}
        rowdict = {'表三乙': [], '表三丙': []}
        datalist = [dataB, dataC]
        for index, name in enumerate(redict):
            temp = []
            rowtemp = []
            for row, rowv in enumerate(datalist[index]):
                if serial == rowv[0] and idnum == rowv[11]:
                    temp.append(rowv)
                    rowtemp.append(row)
            redict[name] = temp
            rowdict[name] = rowtemp
        return [redict, rowdict]

    def FromBCGetARows(self, rows, name):
        # 输入行数rows 输入name（’表三乙‘， '表三丙’）返回表三甲对应行
        dataA = self.note.GetData('表三甲')
        dataB = self.note.GetData(name)
        data = []
        temp = []
        for row in rows:
            data.append(dataB[row])
        for row in data:
            if row[0] != '':
                temp.append(row[0] + '_' + row[11])
        rows = set()
        temp = set(temp)
        for i in temp:
            serial, idnum = i.split('_')
            for row, rowv in enumerate(dataA):
                if rowv[0] == serial and rowv[11] == idnum:
                    rows.add(row)
        rows = list(rows)
        return rows

    def DataRowUp(self, name, row):
        # name为表三名称 
        data = self.note.GetData(name)
        if data[row][0] == '' or row == 0:
            return
        temprow = copy.deepcopy(data[row])
        data.insert(row - 1, temprow)
        data.pop(row + 1)
        grid = self.note.getgrid(name)
        for row, rowv in enumerate(data):
            for col, value in enumerate(rowv):
                grid.SetCellValue(row, col, str(value))

    def DataRowDown(self, name, row):
        # name为表三名称 
        data = self.note.GetData(name)
        datalen = self.getdatalen(name)
        if data[row][0] == '' or row > datalen:
            return
        temprow = copy.deepcopy(data[row])
        data.insert(row + 2, temprow)
        data.pop(row)
        grid = self.note.getgrid(name)
        for row, rowv in enumerate(data):
            for col, value in enumerate(rowv):
                grid.SetCellValue(row, col, str(value))

    def Table4AddData(self, datas, gridrow=0):
        for row in datas:
            mtype = row[4]
            insertrows = self.FindTable4Rows(mtype)
            if mtype == '设备' or mtype == '设备(不安装)':
                gridname = '表四设备'
            else:
                gridname = '表四材料'
            grid = self.note.getgrid(gridname)
            
            if insertrows[0] >= 0:
                temp = self.MakeTable4Row(row)
                thisdatas = copy.deepcopy(self.note.GetData(gridname))
                if gridrow >= insertrows[0] and gridrow <= insertrows[1]:
                    grid.InsertRows(pos=gridrow)
                    thisdatas.insert(gridrow, temp)
                else:
                    grid.InsertRows(pos=insertrows[1] + 1)
                    thisdatas.insert(insertrows[1] + 1, temp)
            else:
                thisdatas = copy.deepcopy(self.note.GetData(gridname))
                isempty = True
                for rowv in thisdatas:
                    for value in rowv:
                        if value != '':
                            isempty = False
                            break
                if isempty:
                    tablelen = 3
                else:
                    tablelen = 1
                    for i in thisdatas:
                        tablelen += 1
                        if i[0] == '总计':
                            break
                    # tablelen = len(thisdatas)
                simrow = [['' for i in range(13)]]
                appendrows = self.genmaterialtotal(simrow)
                temp = self.MakeTable4Row(row)
                temp = [temp, *appendrows[mtype]]
                grid.InsertRows(tablelen - 3, 7)
                if isempty:
                    temp.append(*simrow)
                    temp.append(appendrows['总计'])
                temp.reverse()
                for row in temp:
                    thisdatas.insert(tablelen - 3, row)
            self.note.SetData(thisdatas, gridname)
            self.settable4readonly()

    def Table4DelData(self, thisrow, name):
        data = copy.copy(self.note.GetData(name))
        grid = self.note.getgrid(name)
        typename = data[thisrow][12]
        typenum = 0
        for row in data:
            try:
                if row[12] == typename:
                    typenum += 1
            except IndexError:
                pass
        if typenum > 1:
            grid.DeleteRows(thisrow)
        else:
            grid.DeleteRows(thisrow, 7)
        
        grid = self.note.getgrid(name)
        tableid = grid.GetId()
        eventtype = wx.grid.EVT_GRID_CELL_CHANGED.typeId
        event = wx.grid.GridEvent(tableid, eventtype,
            grid, row=0, col=3)
        wx.PostEvent(grid, event)

    def Table4ChangeData(self, odata, cdata, gridrow=0):
        # datas 格式都为[名称， 规格， 单位， 价格， 类型]
        otype = odata[4]
        ctype = cdata[4]
        if ctype == '设备' or ctype == '设备(不安装)':
            gridname = '表四设备'
        else:
            gridname = '表四材料'
        grid = self.note.getgrid(gridname)
        grid.DeleteRows(gridrow)
        self.Table4AddData([cdata], gridrow)

    def MakeTable4Row(self, data):
        tax = Dec(data[3]) * Dec('0.13')
        sprice = tax + Dec(data[3])
        relist = [data[0], data[1], data[2], '0', data[3], str(tax),
                 str(sprice), '0.0', '0.0', '0.0', '甲供', '1', data[4]]

        return relist
        
    def FindTable4Rows(self, name):
        # 输入材料name 返回可操作的行rows
        if name == '设备' or name == '设备(不安装)':
            gridname = '表四设备'
        else:
            gridname = '表四材料'

        firstrow = -1
        datas = self.note.GetData(gridname)
        for row, rowv in enumerate(datas):
            try:
                if rowv[12] == name:
                    firstrow = row
                    break
            except IndexError:
                pass
        lastrow = -1
        for row, rowv in enumerate(datas[firstrow:]):
            try:
                if rowv[12] != name:
                    lastrow = row - 1 + firstrow
                    break
            except IndexError:
                pass
        
        return (firstrow, lastrow)

    def Table4GetRate(self):
        names = ['表四设备', '表四材料']
        data = self.note.GetData(names[0])
        data.extend(self.note.GetData(names[1]))
        ret = dict()
        material_type = ['光缆', '电缆', '塑料', '木材', '水泥', '其他', '设备', '设备(不安装)']
        colnamelist = ['运杂费', '运输保险费', '采购保管费', '采购代理服务费(直接金额)']
        thisdict = dict()
        for row in data:
            for mtype in material_type:
                for i in colnamelist:
                    name = mtype + i
                    if name in row[0]:
                        if i != '采购代理服务费(直接金额)':
                            thisdict[i] = row[11]
                        else:
                            if row[7] == '' and row[8] == '':
                                thisdict[i] = (0, 0)
                                ret[mtype] = thisdict
                                thisdict = dict()
                            else:
                                thisdict[i] = (row[7], row[8])
                                ret[mtype] = thisdict
                                thisdict = dict()
                
        return ret

    def Table4SetRate(self, ratedata):
        tablenames = ['表四设备', '表四材料']
        for tablename in tablenames:
            data = copy.deepcopy(self.note.GetData(tablename))
            if data[0][:4] == ['', '', '', '']:
                continue
            material_type = ['光缆', '电缆', '塑料', '木材', '水泥', '其他', '设备', '设备(不安装)']
            colnamelist = ['运杂费', '运输保险费', '采购保管费', '采购代理服务费(直接金额)']
            for row in data:
                for mtype in material_type:
                    for i in colnamelist:
                        name = mtype + i
                        if name in row[0]:
                            if i != '采购代理服务费(直接金额)':
                                row[0] = name + '费率:' + str(Dec(ratedata[mtype][i]) * 100) + '%'
                                row[11] = ratedata[mtype][i]
                            else:
                                price = float(ratedata[mtype][i][0])
                                tax = float(ratedata[mtype][i][1])
                                tprice = price + tax
                                if price == 0 and tax == 0:
                                    row[7:10] = ['', '', '']
                                else:
                                    row[7:10] = [price, tax, tprice]
            self.note.SetData(data, tablename)
            grid = self.note.getgrid(tablename)
            tableid = grid.GetId()
            eventtype = wx.grid.EVT_GRID_CELL_CHANGED.typeId
            event = wx.grid.GridEvent(tableid, eventtype,
                grid, row=0, col=3)
            wx.PostEvent(grid, event)

    def Table5AddData(self, datas, gridrow=0):
        self.table5flist.insert(gridrow, datas[0])
        self.table5flist[gridrow] = datas
        grid = self.note.getgrid('表五')
        grid.InsertRows(pos=gridrow)
        self.InitTable5()
        self.RefreshTable5()
        self.settable5readonly()
        self.InitTable1()
        self.RefreshTable1()

    def Table5ChangeData(self, datas, gridrow=0):
        self.table5flist[gridrow] = datas
        self.InitTable5()
        self.RefreshTable5()
        self.settable5readonly()
        self.InitTable1()
        self.RefreshTable1()
    
    def Table5Del(self, row):
        self.table5flist.pop(row)
        grid = self.note.getgrid('表五')
        grid.DeleteRows(row)
        self.InitTable5()
        self.RefreshTable5()
        self.settable5readonly()
        self.InitTable1()
        self.RefreshTable1()

    def Table5GetRate(self):
        ret = []
        ret.append(self.discountss)
        ret.append(self.discountd)
        ret.append(self.discounts)
        ret.append(self.discountsafe)
        ret.append(self.discounta)
        ret.append(self.stage_rate)

        return ret

    def Table5ChangeRate(self, datas):
        self.discountss = datas[0]
        self.discountd = datas[1]
        self.discounts = datas[2]
        self.discountsafe = datas[3]
        self.discounta = datas[4]
        self.stage_rate = datas[5]
        
        self.InitTable5()
        self.RefreshTable5()
        self.InitTable1()
        self.RefreshTable1()

    def GetTaxs(self):
        data = []
        data.append(self.servtax)
        data.append(self.contax)
        data.append(self.matetax)

        return data

    def Table1GetRates(self):
        Data = list(self.table1rate.values())
        return Data

    def Table1SetRates(self, rates):
        Data = list(rates.values())
        for index, key in enumerate(self.table1rate):
            if DataTool().isnum(Data[index]):
                Data[index] = float(Data[index])
            self.table1rate[key] = Data[index]
            
        self.InitTable1()
        self.RefreshTable1()

    def getdatalen(self, name):
        # 返回name表行数
        data = self.note.GetData(name)
        num = 0
        for i in data:
            if i[0] == '':
                break
            num += 1

        return num
    
    def Listlen(self, thislist):
        # 找到list中全是空白的一行
        for ret, i in enumerate(thislist):
            for index, j in enumerate(i):
                leni = len(i)
                if j != '':
                    continue
                else:
                    if index+1 == leni:
                        return ret
    
    def islistempty(self, thislist):
        ret = True
        for i in thislist:
            if i != '':
                ret = False
                break
        
        return ret

    def getbiggestnum(self, thislist):
        # 找到list中最大的idnum
        retnum = 0
        for i in thislist:
            try:
                judgment = self.isnum(i[11])
            except IndexError:
                judgment = False
            if judgment:
                temp = int(float(i[11]))
                if temp > retnum:
                    retnum = temp
        return retnum

    def ExportTemplet(self):
        # 导出模板
        # 导出数据 表三fidct teardict 
        # + 表四数据 fdict + 表二 table2rate ratedisc
        # + 表五 gentable5list 中的 table5flist
        templist = []
        templist.append(self.fdict)
        templist.append(self.teardict)
        templist.append(self.table2rate)
        templist.append(self.table2ratedisc)
        templist.append(self.table2flist)
        templist.append(self.table2flists)
        templist.append(self.table5flist)
        templist.append(self.table1rate)
        return templist
    
    def ImportTemplet(self, templist):
        # 导入模板
        self.fdict = templist[0]
        self.teardict = templist[1]
        self.table2rate = templist[2]
        self.table2ratedisc = templist[3]
        self.table2flist = templist[4]
        self.table2flists = templist[5]
        self.table5flist = templist[6]
        self.table1rate = templist[7]
        
    def ExportData(self):
        # 导出数据
        temp = [self.ExportTemplet()]
        temp.append(self.ExportInitData())
        for name in self.tablestyledata:
            if isinstance(name, tuple):
                name = name[1]
            temp.append((name, self.note.GetData(name)))

        return temp

    def ImportData(self, datalist):
        # 导入数据
        self.ImportTemplet(datalist[0])
        self.ImportInitData(datalist[1])
        for data in datalist[2:]:
            self.note.SetData(data[1], data[0])
        self.initflag = True
        self.RefreshTable2()
        self.PostTable3ChangeEvent()
        self.PostTable4ChangeEvent()
        self.PostTable4ChangeEvent(name='表四设备')
        self.initflag = False

    def ExportInitData(self):
        # 导出初始化数据
        retdict = copy.deepcopy(self.InitDatas)
        for name in retdict:
            retdict[name] = getattr(self, name)

        return retdict

    def ImportInitData(self, data):
        # 导入初始化数据
        for name in self.InitDatas:
            value = data.get(name, self.InitDatas[name])
            setattr(self, name, value)
    
    def GetHandler(self):
        return self
    
    def OnConver2Stand(self, pro):
        StandDatas = {'discount': 100,'discountd': '1', 'discounts': '1', 
                        'discountss': '1', 'discounta': '1',
                        'discountsafe': '1', 'stage_rate': '1'}
        for key in StandDatas:
            setattr(self, key, StandDatas[key])
        
        table1rate = Table1rate(pro, path=os.path.join(self.path, 'rate.db')).getrate()
        self.table1rate = table1rate
        table2rate = Table2rate(
            pro, sc2en_dis=self.sc2en_dis, local=self.local,
            specarea=self.specarea, earth=self.earth, mach_dis=self.mach_dis,
            ton=self.ton, path=os.path.join(self.path, 'rate.db'),
            mech=self.mech, work=self.work).getrate()
            
        conn = SqliteHandler(os.path.join(self.path, 'rate.db'))
        self.table2ratedisc = conn.select('description', flag='list')
        self.table2rate = table2rate

        self.note.getpanel('表二（标）').ratedata = copy.deepcopy(self.table2rate)
        self.note.getpanel('表二（标）').ratedisc = copy.deepcopy(self.table2ratedisc)
        self.note.getpanel('表二').ratedata = copy.deepcopy(self.table2rate)
        self.note.getpanel('表二').ratedisc = copy.deepcopy(self.table2ratedisc)
        self.note.getpanel('表二').discount = self.discount

        grids = (self.table3Bgrid, self.table3Cgrid)
        for index, name in enumerate(('表三乙', '表三丙')):
            data = self.note.GetData(name)
            for row, i in enumerate(data):
                if len(i) > 11 and i[12] == '0':
                    grids[index].SetCellValue(row, 12, '1')
                    arow = self.FromBCGetARows([row], name)[0]
                    self.PostTable3ChangeEvent(arow, 3)
        
        table4rate = Table4rate(self.pro, self.mat_dis, path=os.path.join(self.path, 'rate.db')).getrate()
        material_type = copy.deepcopy(self.material_type)
        retdict = dict()
        for name in material_type:
            temp = dict()
            for key in table4rate:
                if name in key and '(' not in key:
                    thiskey = key.replace(name, '')
                    if thiskey == '运保费':
                        thiskey = '运输保险费'
                    if thiskey == '采购及保管费':
                        thiskey = '采购保管费'
                    temp[thiskey] = Dec(str(table4rate[key])) / Dec('100')
                elif name == key[:7]:
                    thiskey = key.replace(name, '')
                    temp[thiskey] = Dec(str(table4rate[key])) / Dec('100')

            temp['采购代理服务费(直接金额)'] = (0, 0)
            retdict[name] = temp
        self.Table4SetRate(retdict)
        self.PostTable3ChangeEvent()



if __name__ == "__main__":
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    
    class TestFrame(wx.Frame):
      def __init__(self, parent, title):
         super().__init__(parent, -1, title, size = (1000,600))  
         self.InitUI()

      def InitUI(self):    
         # sizer = wx.BoxSizer()   
         test = FrontDataHandler(self, 'book4', path=os.path.join(BASE_DIR, 'db'), table3_specarea='粪坑', table3_specarea_rate=.20)
         # sizer.Add(panel, wx.EXPAND)
         templet = test.ExportTemplet()
    app = wx.App()
    frame = TestFrame(None, 'test')
    frame.Show()
    app.MainLoop()